package org.jeecg.modules.car.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.entity.basedata.BaseProject;
import org.jeecg.entity.car.CarMerchantDerate;
import org.jeecg.enums.car.CarDerateStatusEnum;
import org.jeecg.enums.car.CarDerateTypeEnum;
import org.jeecg.modules.car.entity.CarMerchant;
import org.jeecg.modules.car.entity.CarParkInfo;
import org.jeecg.modules.car.service.ICarMerchantDerateService;
import org.jeecg.modules.car.service.ICarMerchantService;
import org.jeecg.modules.car.service.ICarParkInfoService;
import org.jeecg.modules.car.service.ICarPortService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;

/**
 * @Description: 商家管理
 * @Author: liurui
 * @Date:   2020-10-17
 * @Version: V1.0
 */
@Slf4j
@Api(tags="商家管理")
@RestController
@RequestMapping("/b/car/carMerchant")
public class CarMerchantController {
	 @Autowired
	 private ICarMerchantService carMerchantService;

	 @Autowired
	 private ICarMerchantDerateService carMerchantDerateService;

	 @Autowired
	 private ICarPortService carPortService;

	 @Autowired
	 private ISysUserRoleService sysUserRoleService;

	 @Autowired
	 private ICarParkInfoService carParkInfoService;

	 /**
	  * 分页列表查询
	  *
	  * @param carMerchant
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "商家管理-分页列表查询")
	 @ApiOperation(value = "商家管理-分页列表查询", notes = "商家管理-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<CarMerchant>> queryPageList(CarMerchant carMerchant,
													 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
													 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
													 HttpServletRequest req) {
		 Result<IPage<CarMerchant>> result = new Result<IPage<CarMerchant>>();
		 carMerchant.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(), "p", carMerchant.getMenuPath(), null, carMerchant.getDepartIdEx()));
		 Page<CarMerchant> page = new Page<CarMerchant>(pageNo, pageSize);
		 page.setRecords(carMerchantService.findPage(page, carMerchant));
		 result.setSuccess(true);
		 result.setResult(page);
		 return result;
	 }

	 @AutoLog(value = "根据车场获取所有商家")
	 @ApiOperation(value = "根据车场获取所有商家", notes = "根据车场获取所有商家")
	 @GetMapping(value = "/getMerchantByParkList")
	 public Result getMerchantByParkList(@RequestParam(name = "parkId", required = true) String parkId) {
		 Result<List<CarMerchant>> result = new Result<List<CarMerchant>>();
		 try {
			 List<CarMerchant> list = carMerchantService.getMerchantByParkList(parkId);
			 result.setResult(list);
			 result.setSuccess(true);
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
			 result.error500("获取商家信息失败");
		 }
		 return result;
	 }

	 /**
	  * 添加
	  *
	  * @param carMerchant
	  * @return
	  */
	 @AutoLog(value = "商家管理-添加")
	 @ApiOperation(value = "商家管理-添加", notes = "商家管理-添加")
	 @PostMapping(value = "/add")
	 public Result<CarMerchant> add(@RequestBody CarMerchant carMerchant) {
		 Result<CarMerchant> result = new Result<CarMerchant>();
		 try {
			 CarMerchant exist = carMerchantService.getUserByName(carMerchant.getLoginName());
			 if (exist != null) {
				 return Result.error("手机号已存在,不可重复添加！");
			 }
			 if (carMerchant.getLoginPwd() == null) {
				 return Result.error("请设置初始密码");
			 }
			 String salt = oConvertUtils.randomGen(8);
			 carMerchant.setSalt(salt);
			 carMerchant.setTenantId(SsoUtil.getLoginUser().getTenantId());
//			 String passwordEncode = PasswordUtil.encrypt(carMerchant.getLoginName(), carMerchant.getLoginPwd(), salt);
//			 carMerchant.setLoginPwd(passwordEncode);
			 carMerchantService.save(carMerchant);
			 result.success("添加成功！");
		 } catch (Exception e) {
			 log.error(e.getMessage(), e);
			 result.error500("操作失败");
		 }
		 return result;
	 }

	 /**
	  * 编辑
	  *
	  * @param carMerchant
	  * @return
	  */
	 @AutoLog(value = "商家管理-编辑")
	 @ApiOperation(value = "商家管理-编辑", notes = "商家管理-编辑")
	 @PutMapping(value = "/edit")
	 public Result<CarMerchant> edit(@RequestBody CarMerchant carMerchant) {
		 Result<CarMerchant> result = new Result<CarMerchant>();
		 CarMerchant carMerchantEntity = carMerchantService.getById(carMerchant.getId());
         CarMerchant merchant = carMerchantService.getUserByName(carMerchant.getLoginName());
		 if (merchant != null && !carMerchantEntity.getId().equals(merchant.getId())){
		   return result.error500("登录名称不允许重复");
         }
		 if (carMerchantEntity == null) {
			 result.error500("未找到对应实体");
		 } else {
			 boolean ok = carMerchantService.updateById(carMerchant);
			 //TODO 返回false说明什么？
			 if (ok) {
				 result.success("修改成功!");
			 }
		 }

		 return result;
	 }

	 /**
	  * 通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "商家管理-通过id删除")
	 @ApiOperation(value = "商家管理-通过id删除", notes = "商家管理-通过id删除")
	 @DeleteMapping(value = "/delete")
	 public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		 try {
			 Map<String, Object> map = new HashMap<>();
			 //状态为未使用 && 商家自己发放的不允许删除商家
			 map.put("merchant_id", id);
			 map.put("derate_type", CarDerateTypeEnum.CAR_DERATE_TYPE_0);
			 map.put("status", CarDerateStatusEnum.CAR_DERATE_STATUS_0);
			 List<CarMerchantDerate> carMerchantDerateList = (List<CarMerchantDerate>) carMerchantDerateService.listByMap(map);
			 if (carMerchantDerateList.size() > 0) {
				 return Result.error("当前商户有未使用优惠券，请处理后再删除商家！");
			 }
			 carMerchantService.removeById(id);
		 } catch (Exception e) {
			 log.error("删除失败", e.getMessage());
			 return Result.error("删除失败!");
		 }
		 return Result.ok("删除成功!");
	 }

	 /**
	  * 批量删除
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "商家管理-批量删除")
	 @ApiOperation(value = "商家管理-批量删除", notes = "商家管理-批量删除")
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<CarMerchant> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		 Result<CarMerchant> result = new Result<CarMerchant>();
		 if (ids == null || "".equals(ids.trim())) {
			 result.error500("参数不识别！");
		 } else {
			 List<String> idArr = Arrays.asList(ids.split(","));
			 Map<String, Object> map = new HashMap<>();
			 for (int i = 0; i < idArr.size(); i++) {
				 map.clear();
				 map.put("merchant_id", idArr.get(i));
				 map.put("derate_type", CarDerateTypeEnum.CAR_DERATE_TYPE_0);
				 map.put("status", CarDerateStatusEnum.CAR_DERATE_STATUS_0);
				 List<CarMerchantDerate> carMerchantDerateList = (List<CarMerchantDerate>) carMerchantDerateService.listByMap(map);
				 if (carMerchantDerateList.size() > 0) {
					 return Result.error("所选商户有未使用优惠券，无法执行批量删除操作！");
				 }
			 }
			 this.carMerchantService.removeByIds(Arrays.asList(ids.split(",")));
			 result.success("删除成功!");
		 }
		 return result;
	 }


	 /**
	  * 商户余额充值
	  *
	  * @param merchantId 商户id
	  * @param payAmount 到账金额
	  * @param actualAmount 实付金额
	  * @param payType   支付类型
	  * @param payMode   支付方式
	  * @return
	  */
	 @AutoLog(value = "商家管理-余额充值")
	 @ApiOperation(value = "商家管理-余额充值", notes = "商家管理-余额充值")
	 @GetMapping(value = "/merchantRecharge")
	 public Result<?> merchantRecharge(String merchantId, BigDecimal actualAmount, BigDecimal payAmount, String payType,String payMode, String remarks) {
		 Result<CarMerchant> result = new Result<CarMerchant>();
		 try {
			 CarMerchant carMerchant = carMerchantService.getSelfById(merchantId);
			 if (carMerchant == null) {
				 return result.error500("未查询到该商户信息");
			 }
			 result = carMerchantService.merchantPay(carMerchant, payAmount,actualAmount, remarks, payType,payMode);
		 } catch (Exception e) {
			 log.error("充值失败", e.getMessage());
			 return Result.error("充值失败!");
		 }
		 return result;
	 }

	/**
	 * 商户积分充值
	 *
	 * @param merchantId 商户id
	 * @param payAmount 充值金额
	 * @param payType   支付类型
	 * @return
	 */
	@AutoLog(value = "商家管理-积分充值")
	@ApiOperation(value = "商家管理-积分充值", notes = "商家管理-积分充值")
	@GetMapping(value = "/merchantDonateRecharge")
	public Result<?> merchantDonateRecharge(String merchantId, double payAmount, String payMode, String remarks) {
		Result<CarMerchant> result = new Result<CarMerchant>();
		try {
			CarMerchant carMerchant = carMerchantService.getSelfById(merchantId);
			if (carMerchant == null) {
				return result.error500("未查询到该商户信息");
			}

			result = carMerchantService.merchantDonateRecharge(carMerchant, payAmount, payMode, remarks);
		} catch (Exception e) {
			log.error("充值失败", e.getMessage());
			return Result.error("充值失败!");
		}
		return result;
	}

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "商家管理-通过id查询")
	 @ApiOperation(value = "商家管理-通过id查询", notes = "商家管理-通过id查询")
	 @GetMapping(value = "/queryById")
	 public Result<CarMerchant> queryById(@RequestParam(name = "id", required = true) String id) {
		 Result<CarMerchant> result = new Result<CarMerchant>();
		 CarMerchant carMerchant = carMerchantService.getById(id);
		 if (carMerchant == null) {
			 result.error500("未找到对应实体");
		 } else {
			 result.setResult(carMerchant);
			 result.setSuccess(true);
		 }
		 return result;
	 }

	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param response
	  */
	 @RequestMapping(value = "/exportXls")
	 public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
		 // Step.1 组装查询条件
		 QueryWrapper<CarMerchant> queryWrapper = null;
		 try {
			 String paramsStr = request.getParameter("paramsStr");
			 if (oConvertUtils.isNotEmpty(paramsStr)) {
				 String deString = URLDecoder.decode(paramsStr, "UTF-8");
				 CarMerchant carMerchant = JSON.parseObject(deString, CarMerchant.class);
				 queryWrapper = QueryGenerator.initQueryWrapper(carMerchant, request.getParameterMap());
			 }
		 } catch (UnsupportedEncodingException e) {
			 e.printStackTrace();
		 }

		 //Step.2 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 List<CarMerchant> pageList = carMerchantService.list(queryWrapper);
		 //导出文件名称
		 mv.addObject(NormalExcelConstants.FILE_NAME, "商家管理列表");
		 mv.addObject(NormalExcelConstants.CLASS, CarMerchant.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商家管理列表数据", "导出人:Jeecg", "导出信息"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		 return mv;
	 }

	 /**
	  * 通过excel导入数据
	  *
	  * @param request
	  * @param response
	  * @return
	  */
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
             // 获取上传文件对象
             MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 int titleRow = 0;
			 params.setTitleRows(titleRow);
			 params.setHeadRows(titleRow);
			 params.setNeedSave(true);
			 try {
				 List<CarMerchant> listCarMerchant = ExcelImportUtil.importExcel(file.getInputStream(), CarMerchant.class, params);
				 if (listCarMerchant.size() <= 0) {
					 return Result.error("文件内容为空，导入失败！");
				 }
				 //判断excel中是否有相同的登录名
				 Set<String> setMerchant = new HashSet<>();
				 for (CarMerchant carMerchant : listCarMerchant){
				 	setMerchant.add(carMerchant.getLoginName());
				 }
				 if (listCarMerchant.size() != setMerchant.size()){
				 	return Result.error("导入数据中存在相同的登录名，导入失败！");
				 }
				 int successNum = 0;
				 int failureNum = 0;
				 StringBuilder failureMsg = new StringBuilder();
				 for (CarMerchant carMerchant : listCarMerchant) {
					 titleRow++;
					 if (StringUtils.isBlank(carMerchant.getProjectName())) {
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入项目名称; ");
						 failureNum++;
						 continue;
					 }
					 if (StringUtils.isBlank(carMerchant.getName())) {
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入商户名称; ");
						 failureNum++;
						 continue;
					 }
					 if (StringUtils.isBlank(carMerchant.getLoginName())) {
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入登录名; ");
						 failureNum++;
						 continue;
					 }
					 if (StringUtils.isBlank(carMerchant.getParkName())) {
						 failureMsg.append("<br/>第").append(titleRow).append("行：请输入车场名称; ");
						 failureNum++;
						 continue;
					 }
					 CarMerchant merchant = carMerchantService.getUserByName(carMerchant.getLoginName());
					 if (merchant != null) {
						 failureMsg.append("<br/>第").append(titleRow).append("行：登录名称重复");
						 failureNum++;
						 continue;
					 }
					 BaseProject baseProject = carPortService.getProjectByName(carMerchant.getProjectName());
					 if (baseProject == null) {
						 failureMsg.append("<br/>第").append(titleRow).append("行：填写的项目名称系统中不存在; ");
						 failureNum++;
						 continue;
					 }
					 CarParkInfo carParkInfo = carParkInfoService.getByProjectIdAndParkName(baseProject.getId(),carMerchant.getParkName());
					 if (carParkInfo == null){
						 failureMsg.append("<br/>第").append(titleRow).append("行：填写的车场名称系统中不存在; ");
						 failureNum++;
						 continue;
					 }
					 //项目名称id
					 carMerchant.setProjectId(baseProject.getId());
					 //车场id
					 carMerchant.setParkId(carParkInfo.getId());
					 //随机密码
					 carMerchant.setLoginPwd(((int)((Math.random()*9+1)*100000)+""));
				 }
				 if (failureNum > 0 ){
					 return Result.error("文件导入失败:" + failureMsg.toString());
				 }
				 carMerchantService.saveBatch(listCarMerchant);
				 return Result.ok("文件导入成功！数据行数:" + listCarMerchant.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.ok("文件导入失败！");
 	}
}
